//
//  JiluViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/17.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher


@objc class JiluViewController: BaseViewController {

    var isTarget = true
    var targetRect = CGRect()
    
    var tabzhuangtai = 1
    
    
    
    var dingdanArray = [[String:Any]]()
    
    
    var quanbu = [[String:Any]]()
    var daizhifu = [[String:Any]]()
    var weishiyong = [[String:Any]]()
    
    @IBOutlet weak var jiluTableView: UITableView!
    
    @IBOutlet weak var jiluTabBar: UITabBar!
    
    @IBOutlet weak var oneItem: UITabBarItem!
    
    @IBOutlet weak var twoItem: UITabBarItem!
    
    @IBOutlet weak var threeItem: UITabBarItem!
    
    @IBOutlet weak var xiahuaView: UIView!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //self.navigationController?.setNavigationBarHidden(false, animated: true)
        jiluTabBar.selectedItem = oneItem
        jiluTableView.tableFooterView = UIView(frame: CGRect.zero)
        jiluTabBar.tintColor = UIColor(red: 84/255, green: 155/255, blue: 219/255, alpha: 1)
        xiahuaView.frame = CGRect(x: 0, y: 110, width: mainScreenW/3, height:3)
        showdingdan()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = false
    }

    func showdingdan(){
        self.dingdanArray = []
        self.jiluTableView.reloadData()
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let yhid = ["name":"\(y)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/showdingdanindex?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: yhid).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                self.dingdanArray = json["app_all"].arrayObject as! [[String : Any]]
                self.jiluTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    
    func weizhifudingdan(){
        self.dingdanArray = []
        self.jiluTableView.reloadData()
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let yhid = ["name":"\(y)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/showdingdannopay?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: yhid).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                self.dingdanArray = json["app_all"].arrayObject as! [[String : Any]]
                self.jiluTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    
    func weishiyongdingdan(){
        self.dingdanArray = []
        self.jiluTableView.reloadData()
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let yhid = ["name":"\(y)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/showdingdannouse?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: yhid).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                self.dingdanArray = json["app_all"].arrayObject as! [[String : Any]]
                self.jiluTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    func shanchudingdan(dh:String){
        let par = ["ddh":"\(dh)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/deldingdan2?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: par).responseJSON {Request in
            switch Request.result {
            case .success:
                //let json = JSON(data: Request.data!)
                if self.tabzhuangtai == 1 {
                    self.showdingdan()
                } else if self.tabzhuangtai == 2 {
                    self.weizhifudingdan()
                } else if self.tabzhuangtai == 3 {
                    self.weishiyongdingdan()
                }
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    

}

extension JiluViewController: UITabBarDelegate, UITableViewDelegate, UITableViewDataSource {
    
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        switch item.tag {
        case 1:
            tabzhuangtai = 1
            UITableView.animate(withDuration: 0.2, animations: {
                self.xiahuaView.frame = CGRect(x: 0, y: 110, width: mainScreenW/3, height:3)})
            showdingdan()
            jiluTableView.reloadData()
        case 2:
            tabzhuangtai = 2
            UITableView.animate(withDuration: 0.2, animations: {
                self.xiahuaView.frame = CGRect(x: mainScreenW/3, y: 110, width: mainScreenW/3, height:3)})
            weizhifudingdan()
            jiluTableView.reloadData()
        case 3:
            tabzhuangtai = 3
            UITableView.animate(withDuration: 0.2, animations: {
                self.xiahuaView.frame = CGRect(x: mainScreenW - mainScreenW/3, y: 110, width: mainScreenW/3, height:3)})
            weishiyongdingdan()
            jiluTableView.reloadData()
        default:
            break
        }
    }
    
    func setup(cell: XiaofeiJiluTableViewCell, atIndexPath indexPath: IndexPath) {
        let  or = "\(dingdanArray[indexPath.row]["img_url"]!)"
        let url = URL(string:or)
        
        if cell.shopImg.kf.webURL != url {
            let cellFrame = self.jiluTableView.rectForRow(at: indexPath)
            var shouldLoadImage = true
            if self.isTarget && !self.targetRect.intersects(cellFrame) {
                let image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: or, options: nil)
                if image == nil {
                    shouldLoadImage = false
                }
            }
            if shouldLoadImage {
                cell.shopImg.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {                    }})}}}
    

    
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return dingdanArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XiaofeiJiluTableViewCell", for: indexPath) as! XiaofeiJiluTableViewCell
        cell.pingjiaBtn.isHidden = true
        cell.zlaiyidanBtn.isHidden = true
        cell.shopTit.text = "\(dingdanArray[indexPath.row]["shopname"]!)"
        cell.timeLab.text = "\(dingdanArray[indexPath.row]["created_at"]!)"
        cell.zongjiaLab.text = "\(dingdanArray[indexPath.row]["name"]!)" + "等" + "\(dingdanArray[indexPath.row]["number"]!)" + "款商品，共计" + "\(dingdanArray[indexPath.row]["allprice"]!)" + "元"
        self.setup(cell: cell, atIndexPath: indexPath)
        let x = "\(dingdanArray[indexPath.row]["state"]!)"
        switch x {
        case "\(0)":
            cell.zhangtaiLab.text = "待支付"
        case "\(1)":
            cell.zhangtaiLab.text = "待使用"
        case "\(2)":
            cell.zhangtaiLab.text = "已使用"
        default:
            break
        }


        return cell
    }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            jiluTableView.deselectRow(at: indexPath, animated: false)
            ddh = "\(self.dingdanArray[indexPath.row]["ddh"]!)"
            
            let sb = UIStoryboard(name: "Main", bundle:nil)
            let secondViewController = sb.instantiateViewController(withIdentifier: "dingdanxiangqing") as! UINavigationController
            self.present(secondViewController, animated: true, completion: nil)

    }

    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 65
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        self.targetRect = CGRect(x: targetContentOffset.pointee.x, y: targetContentOffset.pointee.y, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        self.isTarget = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.isTarget = false
        self.loadImageForVisibleCells()
    }
    
    func loadImageForVisibleCells() {
        let visibleCells = self.jiluTableView.visibleCells
        for cell in visibleCells {
            self.setup(cell: cell as! XiaofeiJiluTableViewCell, atIndexPath: self.jiluTableView.indexPath(for: cell)!)
        }
    }
    
    
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        jiluTableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
    }
    
    
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        if tabzhuangtai == 1 {
            let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除",handler: { (action, indexPath) -> Void in
                let x = self.dingdanArray.count
                if x == 0 {
                    return
                } else if x != 0 {
                    let x = "\(self.dingdanArray[indexPath.row]["ddh"]!)"
                    self.shanchudingdan(dh:x)
                }
                
            })
            return [deleteAction]
        } else if tabzhuangtai == 2 {
            let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除",handler: { (action, indexPath) -> Void in
                let x = self.dingdanArray.count
                if x == 0 {
                    return
                } else if x != 0 {
                    let x = "\(self.dingdanArray[indexPath.row]["ddh"]!)"
                    self.shanchudingdan(dh:x)
                }
                
            })
            return [deleteAction]
        } else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if tabzhuangtai == 1 || tabzhuangtai == 2 {
            return true
        } else {
            return false
        }
    }


    
}

